<template>
  <el-container
    class="container"
    v-loading="isUpdating"
    element-loading-text="上传中"
    element-loading-spinner="el-icon-loading"
  >

    <el-badge :value="compareValue.FEV1>0?'+'+compareValue.FEV1:'-'+Math.abs(compareValue.FEV1)" class="tips fev1" :type="compareValue.FEV1>0?'success':'danger'">
      <el-tag  type="info">参考值：{{stadardValue.FEV1}}</el-tag>
    </el-badge>
    
    <el-badge :value="compareValue.FVC>0?'+'+compareValue.FVC:'-'+Math.abs(compareValue.FVC)" class="tips fvc" :type="compareValue.FVC>0?'success':'danger'">
    <el-tag  type="info">参考值：{{stadardValue.FVC}}</el-tag>
    </el-badge>
    
    <el-badge :value="compareValue.PEF>0?'+'+compareValue.PEF:'-'+Math.abs(compareValue.PEF)" class="tips pef" :type="compareValue.PEF>0?'success':'danger'">
    <el-tag  type="info">参考值：{{stadardValue.PEF}}</el-tag>
    </el-badge>
    
    <el-badge :value="compareValue.Ratio>0?'+'+compareValue.Ratio:'-'+Math.abs(compareValue.Ratio)" class="tips ratio" :type="compareValue.Ratio>0?'success':'danger'">
    <el-tag  type="info">参考值：{{stadardValue.Ratio}}</el-tag>
    </el-badge>

    

    <el-container>
      <el-aside width="35%" class="aside-lpd">
        <el-row class="chart-bg">
          <EChart
            container="chart1"
            width="100%"
            height="400px"
            :option="option1"
          ></EChart>
        </el-row>
        <el-row class="chart-bg">
          <EChart
            container="chart5"
            width="100%"
            height="400px"
            :option="option2"
          ></EChart>
        </el-row>
      </el-aside>
      <el-main class="main-pd">
        <el-row class="chart-bg">
          <el-col :span="12">
            <EChart
              container="chart2"
              width="100%"
              height="400px"
              :option="option3"
            ></EChart>
          </el-col>
          <el-col :span="12">
            <EChart
              container="chart3"
              width="100%"
              height="400px"
              :option="option4"
            ></EChart>
          </el-col>
        </el-row>
        <el-row class="chart-bg">

            <EChart
              container="chart4"
              width="100%"
              height="400px"
              :option="option5"
            ></EChart>
        </el-row>
      </el-main>
      <!-- 抽屉 -->

      <el-drawer :visible.sync="isVisiable" direction="rtl" :with-header="false">
        <el-aside width="100%">
          <el-row class="aside-pd">
            <div class="user-info">
              <div class="title">用户信息</div>
              <div class="sub-info">姓名：{{ userMsg.name }}</div>
              <div class="sub-info">性别：{{ userMsg.gender }}</div>
              <div class="sub-info">年龄：{{ userMsg.age }}</div>
              <div class="sub-info">身高：{{ userMsg.height }}cm</div>
              <div class="sub-info">体重：{{ userMsg.weight }}kg</div>
            </div>
            <div class="change-btn" @click="toTrain">
              前往训练页面
              <img src="paitan.png" alt="" class="btn-img" />
            </div>
            <!-- <div class="change-btn" @click="onloadData">
              上传数据
              <img src="paitan.png" alt="" class="btn-img" />
            </div> -->
          </el-row>
        </el-aside>
      </el-drawer>
      <el-button class="prefix" type="primary" @click="isVisiable = true">菜单栏</el-button>
    </el-container>
  </el-container>
</template>

<script>
import EventBus from "../utils/eventbus.js";
import { sendData } from "../api/index";
import { mapState } from "vuex";
export default {
  name: "Paitan",

  data() {
    return {
      isVisiable: false,
      isUpdating: false,
      userMsg: {},
      chart1Data: new Array(10).fill(0),
      chart2Data: new Array(10).fill(0),
      chart3Data: new Array(10).fill(0),
      chart4Data: new Array(10).fill(0),
      chart5Data: new Array(10).fill(0),
    };
  },
  computed: {
    option1() {
      let _this = this;
      let xData = [];
      for(let i=0;i<this.chart1Data.length;i++){
          xData[i]=i+'s'
      }
      return {
        title: {
          text: "第一秒用力呼气容积(FEV1)",
        },
        tooltip: {},
        xAxis: {
          data: xData,
        },
        yAxis: {
          axisLabel: {
            formatter: "{value} L",
            align: "center",
          },
        },
        series: [
          {
            name: "第一秒用力呼气容积(FEV1)",
            type: "line",
            data: _this.chart1Data,
          },
        ],
      };
    },
    option2() {
      let _this = this;
            let xData = [];
      for(let i=0;i<this.chart1Data.length;i++){
          xData[i]=i+'s'
      }
      return {
        title: {
          text: "用力肺活量(FVC)",
        },
        tooltip: {},
        xAxis: {
          data: xData,
        },
        yAxis: {
                    axisLabel: {
            formatter: "{value} L",
            align: "center",
          },
        },
        series: [
          {
            name: "用力肺活量(FVC)",
            type: "line",
            data: _this.chart2Data,
          },
        ],
      };
    },
    option3() {
      let _this = this;
                  let xData = [];
      for(let i=0;i<this.chart1Data.length;i++){
          xData[i]=i+'s'
      }
      return {
        title: {
          text: "FEV1/FVC",
        },
        tooltip: {},
        xAxis: {
          data: xData,
        },
        yAxis: {
                    axisLabel: {
            formatter: "{value} %",
            align: "center",
          },
        },
        series: [
          {
            name: "FEV1/FVC",
            type: "line",
            data: _this.chart3Data,
          },
        ],
      };
    },
    option4() {
      let _this = this;
                  let xData = [];
      for(let i=0;i<this.chart1Data.length;i++){
          xData[i]=i+'s'
      }
      return {
        title: {
          text: "峰流速值(PEF)",
        },
        tooltip: {},
        xAxis: {
          data: xData,
        },
        yAxis: {
                    axisLabel: {
            formatter: "{value} L/sec",
            align: "center",
          },
        },
        series: [
          {
            name: "峰流速值(PEF)",
            type: "line",
            data: _this.chart4Data,
          },
        ],
      };
    },
    option5() {
      let _this = this;
                  let xData = [];
      for(let i=0;i<this.chart1Data.length;i++){
          xData[i]=i+'min'
      }
      return {
        title: {
          text: "呼吸频率",
        },
        tooltip: {},
        xAxis: {
          data:xData,
        },
        yAxis: {
                    axisLabel: {
            formatter: "{value} 次/min",
            align: "center",
          },
        },
        series: [
          {
            name: "呼吸频率",
            type: "line",
            data: _this.chart5Data,
          },
        ],
      };
    },
    stadardValue(){
      let FEV1 = 0,FVC =0,PEF =0,Ratio= 0
      if(this.userMsg.gender==='男'){
        FEV1 = (0.93*1.08*((0.043*this.userMsg.height)-(0.029*this.userMsg.age)-2.49)).toFixed(2)
        FVC = (0.93*1.1*((0.0576*this.userMsg.height)-(0.0269*this.userMsg.age)-4.34)).toFixed(2)
        PEF=(Math.exp(((0.544*Math.log(this.userMsg.age))-0.0151*this.userMsg.age-74.7/this.userMsg.height)+5.48)).toFixed(2)  
        Ratio = (87.2-0.18*this.userMsg.age).toFixed(2)
      }else if(this.userMsg.gender==='女'){
        FEV1 = (0.93*1.08*((0.0395*this.userMsg.height)-(0.025*this.userMsg.age)-2.6)).toFixed(2)
        FVC = (0.93*1.15*((0.0443*this.userMsg.height)-(0.026*this.userMsg.age)-2.89)).toFixed(2)
        PEF=(Math.exp(((0.376*Math.log(this.userMsg.age))-0.012*this.userMsg.age-58.8/this.userMsg.height)+5.63)).toFixed(2)  
        Ratio = (89.1-0.19*this.userMsg.age).toFixed(2)
      }
      return {
        FEV1,
        FVC,
        PEF,
        Ratio
      }
    },
    compareValue(){
      let averageFev1 = (this.chart1Data.reduce((p,c)=>p+c)/this.chart1Data.length).toFixed(2)
      let averageFvc = (this.chart2Data.reduce((p,c)=>p+c)/this.chart1Data.length).toFixed(2)
      let averagePef = (this.chart4Data.reduce((p,c)=>p+c)/this.chart1Data.length).toFixed(2)
      let averageRatio = (this.chart3Data.reduce((p,c)=>p+c)/this.chart1Data.length).toFixed(2)
      return {
        FEV1:(averageFev1-this.stadardValue.FEV1).toFixed(2),
        FVC:(averageFvc-this.stadardValue.FVC).toFixed(2),
        PEF:(averagePef-this.stadardValue.PEF).toFixed(2),
        Ratio:(averageRatio-this.stadardValue.Ratio).toFixed(2)
      }
    }
  },
  methods: {
    changeOptionData() {
      const result = localStorage.getItem("result");
      if(result){
      const dataArr = result.split("|");
        this.chart1Data = dataArr[0].split(",").map((item) => Number(item));
        this.chart2Data = dataArr[1].split(",").map((item) => Number(item));
        this.chart3Data = dataArr[2].split(",").map((item) => Number(item));
        this.chart4Data = dataArr[3].split(",").map((item) => Number(item));
        this.chart5Data = dataArr[4].split(",").map((item) => Number(item));
      }
      console.log("排痰界面result：", result);
    },
    onloadData() {
      const result = localStorage.getItem("result");
      const userMsg = JSON.parse(localStorage.getItem('userMsg'))
      const dataArr = result.split("|");
      let Fev1Arr = dataArr[0].split(',').map(i=>Number(i))
      let FvcArr = dataArr[1].split(',').map(i=>Number(i))
      let RatioArr = dataArr[2].split(',').map(i=>Number(i))
      let PefArr = dataArr[3].split(',').map(i=>Number(i))
      let RRArr = dataArr[4].split(',').map(i=>Number(i))

      let averageFev1 = (Fev1Arr.reduce((p,c)=>p+c)/Fev1Arr.length).toFixed(2)
      let averageFvc = (FvcArr.reduce((p,c)=>p+c)/FvcArr.length).toFixed(2)
      let averageRatio = (RatioArr.reduce((p,c)=>p+c)/RatioArr.length).toFixed(2)
      let averagePef = (PefArr.reduce((p,c)=>p+c)/PefArr.length).toFixed(2)
      let averageRR = (RRArr.reduce((p,c)=>p+c)/RRArr.length).toFixed(2)
        const queryStr = `username=${userMsg.name}&FEV1=${averageFev1}&FVC=${averageFvc}&FEV1_FVC=${averageRatio}&PEF=${averagePef}&RR=${averageRR}`
        // this.isUpdating = true;
        // const result = await sendData(queryStr);
        // this.isUpdating = false;

        // if (result) {
        //   this.$alert("数据上传成功", "提示", {
        //     confirmButtonText: "确定",
        //   });
        // } else {
        //   this.$alert("数据上传失败", "提示", {
        //     confirmButtonText: "确定",
        //   });
        // }
        window.socket.send("res|"+queryStr);
        console.log("res|"+queryStr)
    },
    toTrain() {
      this.$router.push("/train");
    },
    showData(msg) {
      console.log("socketMsg:", msg);
    },

  },
  mounted() {
    this.userMsg = JSON.parse(localStorage.getItem("userMsg"));
    this.changeOptionData();
    this.onloadData()
    EventBus.$on("socketMsg", this.showData);
  },
  beforeDestroy(){
    console.log('清空训练结果数据')
    localStorage.removeItem('result')
  },
  destroyed() {
    EventBus.$off("socketMsg", this.showData);
  },
};
</script>

<style lang='less' scoped>
.container{
  margin-top: 90px;
}
.tips{
  z-index: 99;
  font-size: 20px;
  position: absolute;
  pointer-events: none;
}
.fev1{
  top: 15vh;
  left:380px;
}
.fvc{
  top: 60vh;
  left:380px;
}

.ratio{
  top: 15vh;
  left:980px;
}

.pef{
  top: 15vh;
  left:1580px;
}


.prefix {
  position: fixed;
  top: 50%;
  right: 0;
}
.chart-bg {
  background-color: #fff;
}
.user-info {
  width: 300px;
  background-color: #fff;
  line-height: 20px;
  border-radius: 10px;
  margin-bottom: 60px;
  border: 2px solid #009fc7;
}
.title {
  font-size: 33px;
  font-weight: 600;
  line-height: 60px;
  margin-top: 20px;
  margin-bottom: 30px;
}
.sub-info {
  font-size: 24px;
  line-height: 24px;
  margin-top: 40px;
  margin-bottom: 40px;
  text-align: left;
  padding-left: 40px;
}
.aside-lpd {
  padding: 20px;
}

.btn {
  width: 250px;
  height: 60px;
  background-color: #37d7ff;
  border: 1px solid #009fc7;
  color: #fff;
  font-size: 40px;
  font-weight: 600;
  margin-bottom: 50px;
  border-radius: 20px;
  line-height: 60px;
  cursor: pointer;
}
.btn-img {
  width: 60px;
  height: 60px;
  margin-left: 20px;
}
.change-btn {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 300px;
  height: 100px;
  text-align: center;
  font-size: 30px;
  color: #009fc7;
  background-color: #fff;
  line-height: 100px;
  font-weight: 600;
  border-radius: 30px;
  border: 3px solid #ccc;
  cursor: pointer;
  margin-bottom: 40px;
}
.el-header,
.el-footer {
  background-color: #b3c0d1;
  color: #333;
  text-align: center;
  line-height: 60px;
}
.el-aside {
  background-color: #d3dce6;
  color: #333;
  text-align: center;
  line-height: 200px;
}
.el-main {
  background-color: #e9eef3;
  color: #333;
  text-align: center;
  line-height: 160px;
}
.el-aside[data-v-181b9bba]{
  height: 100%;
  .aside-pd {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    margin-top: 45px;
  }
}
</style>
